<!--
 * @Description: 文件描述
 * @Version: 1.0
 * @Author: YueXuanzi
 * @Date: 2024-09-04 10:47:25
 * @LastEditors: YueXuanzi
 * @LastEditTime: 2024-10-08 20:54:31
 * @心得体会: 无
-->
<template>
    <div class="header flex justify-between items-center w-full h-full">
        <div class="l-content flex justify-center items-center">
            <el-button size="small" class="mr-5" @click="handleCollapse">
                <el-icon class="icons w-3"><Menu/></el-icon>
            </el-button>
            <el-breadcrumb separator="/">
                <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="r-content">
            <el-dropdown class="mr-10">
                <div class="el-dropdown-link w-30 flex justify-center items-center">
                    <!-- <img :src="" alt="" class="user w-7 h-7 rounded-full"/> -->
                    <el-avatar v-if="type != 2" :src="getImgUrl('xx')" :size="30"/>
                    <el-avatar v-else :src="doctorImg" :size="30"/>
                   <div class="text-gray-800 text-xl font-bold ml-2"> {{ name }}</div>
                </div>
                <template #dropdown>
                <el-dropdown-menu>
                    <el-dropdown-item v-if="type == 2" @click="dialogVisible2 = true">修改头像</el-dropdown-item>
                    <el-dropdown-item v-if="type == 0" @click="dialogVisible3 = true">查询余额</el-dropdown-item>
                    <el-dropdown-item @click="dialogVisible = true">修改密码</el-dropdown-item>
                    <el-dropdown-item @click="logoutX">退出</el-dropdown-item>
                </el-dropdown-menu>
                </template>
            </el-dropdown>
        </div>
    </div>
    <el-dialog v-model="dialogVisible" title="修改密码" width="30%">
        <el-form :model="form" label-width="80px">
            <el-form-item label="旧密码">
                <el-input v-model="form.password" placeholder="请输入旧密码" type="password"/>
            </el-form-item>
            <el-form-item label="新密码">
                <el-input v-model="form.newPassword" placeholder="请输入新密码" type="password"/>
            </el-form-item>
            <el-form-item label="确定密码">
                <el-input v-model="newPassword2" placeholder="请输入新密码" type="password"/>
            </el-form-item>
            <el-form-item label="提交">
                <el-button @click="updataPassword">提交</el-button>
                <el-button @click="cencel">取消</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>
    <!-- 医生修改头像 -->
    <el-dialog v-model="dialogVisible2" title="修改图片" width="30%">
        <el-upload  
            action="#"  
            :on-preview="handlePreview"  
            :on-remove="handleRemove"  
            :file-list="fileList"  
            :on-success="handleSuccess"  
            :before-upload="beforeUpload"  
            multiple  
            :limit="3"  
            :on-exceed="handleExceed"  
            :auto-upload="false"  
            :http-request="customRequest"  
        >  
            <el-button  size="small" type="primary">选取文件</el-button>  
            <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>  
            <div class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>  
        </el-upload> 
    </el-dialog>
    <el-dialog v-model="dialogVisible3" title="查询余额" width="30%">
        <el-form :model="form" label-width="80px">
            <el-form-item label="余额">
                <el-text type="primary">{{userStore.getters.getUser.balance}}</el-text>
            </el-form-item>
            <el-form-item label="充值">
                <el-input v-model="money" placeholder="请输入金额"/>
                输入后出现二维码（当前未融入支付宝）
                <el-button @click="recharge">充值</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>
    
</template>

<script setup>
import { ref, computed, reactive } from 'vue'
import { useAllDateStore } from "@/stores";
import { userDateStore } from "@/stores/user";
import { logout, updata, addYue } from "@/api/sys/login.js"
import { ElNotification } from 'element-plus'
import { useRouter } from "vue-router";
import {useCookies} from '@vueuse/integrations/useCookies';
const router = useRouter();
import { removeToken } from '@/utils/auth.js'

const cookies = useCookies()
const getImgUrl = (user)=>{
    return new URL(`../assets/img/${user}.png`, import.meta.url).href
}
const doctorImg = computed(()=>{
    return userStore.getters.getUser.doctorImg
})
const type = computed(()=>{
    return cookies.get("type")
})

const store = useAllDateStore()
const userStore = userDateStore()
const name = computed(()=>{
    return userStore.getters.getUser.username
})
const handleCollapse = ()=>{
    store.state.isCollapse = !store.state.isCollapse
}
let dialogVisible = ref(false)
let dialogVisible2 = ref(false)
let dialogVisible3 = ref(false)
let money = ref("");
// 点击退出
const logoutX = ()=>{
    logout().then(res =>{
        console.log(res)
        if(res.code === 200){
            ElNotification({
                title: '退出成功',
                message: res.msg,
                type: 'success',
            })
            removeToken()
            router.push('/login')
        }else{
            ElNotification({
                title: '失败',
                message: res.msg,
                type: 'error',
            })
        }
    })
}
let newPassword2 = ref("")
// 修改密码
let form = reactive({
    password: "",
    newPassword : "",
    typeX : cookies.get("type")
})
const updataPassword = ()=>{
    if(form.newPassword !== newPassword2.value){
        ElNotification({
            title: '两次密码不一致',
            message: '请重新输入',
            type: 'error',
        })
    }else{
        
        const formInfo = {
            password : form.password,
            newPassword : form.newPassword,
            typeX : form.typeX
        }
        console.log(formInfo)
        updata(formInfo).then(res =>{
            console.log(res)
            if(res.code === 200){
                ElNotification({
                    title: '修改成功',
                    message: res.msg,
                    type: 'success',
               })
               dialogVisible = ref(false)
            }
        })
    }
}
// 取消
const cencel = ()=>{
    dialogVisible = ref(false)
    form = reactive({
        password: "",
        newPassword : "",
        type : cookies.get("type")
    })
}

const fileList = ref([]);  
  
const handlePreview = (file) => {  
    console.log(file);  
};  
  
const handleRemove = (file, fileList) => {  
    console.log(file, fileList);  
};  
  
const handleSuccess = (response, file, fileList) => {  
    console.log(response, file, fileList);  
    ElMessage.success(`${file.name} 文件上传成功`);  
};  
  
const beforeUpload = (file) => {  
    const isJPG = file.type === 'image/jpeg';  
    const isPNG = file.type === 'image/png';  
    const isLt2M = file.size / 1024 / 1024 < 0.5;  

    if (!isJPG && !isPNG) {  
    ElMessage.error('上传头像图片只能是 JPG/PNG 格式!');  
    }  
    if (!isLt2M) {  
    ElMessage.error('上传头像图片大小不能超过 500KB!');  
    }  
    return isJPG && isLt2M || isPNG && isLt2M;  
};  
  
const handleExceed = (files, fileList) => {  
    ElMessage.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);  
};  
  
const submitUpload = () => {  
    fileList.value.forEach((file) => {  
    if (!file.response) {  
        // 手动上传  
        customRequest({  
        file,  
        onProgress: (event) => {  
            console.log(event.percent);  
        },  
        onSuccess: () => {  
            ElMessage.success(`${file.name} 文件上传成功`);  
        },  
        onError: () => {  
            ElMessage.error(`${file.name} 文件上传失败`);  
        },  
        });  
    }  
    });  
};  

const customRequest = ({ file, onProgress, onSuccess, onError }) => {  
    let formData = new FormData();  
    formData.append('file', file);  
    // 你可以在这里添加额外的请求头或参数  
    handleFileUpload(formData).then((response) => response.json())  
    .then((data) => {  
        onSuccess(data);  
        file.response = data; // 你可以在这里保存服务器返回的文件信息  
    })  
    .catch((error) => {  
        onError(error);  
    });   
};  
const recharge = ()=>{
    console.log(money)
    addYue(money.value).then(res =>{
        console.log(res)
        if(res.code === 200){
            ElNotification({
                title: '充值成功',
                message: res.msg,
                type: 'success',
            })
            dialogVisible3 = ref(false)
        }
    })
}
</script>

<style scoped>

</style>